import { reactive } from 'vue';

interface SyncState {
  isAudioReady: boolean;
  // 我们用一个唯一的ID（比如AI消息的ID）来标记每一轮对话，防止信号串扰
  currentSyncId: string | null; 
}

class SyncService {
  public state = reactive<SyncState>({
    isAudioReady: false,
    currentSyncId: null,
  });

  /**
   * 开始一个新的同步会话（当AI开始回复时调用）
   * @param syncId - 当前AI消息的唯一ID
   */
  public startSession(syncId: string): void {
    console.log(`[SyncService] Starting new session for ID: ${syncId}`);
    this.state.currentSyncId = syncId;
    this.state.isAudioReady = false;
  }

  /**
   * 标记音频已准备好（当第一块音频数据到达时调用）
   * @param syncId - 必须与 startSession 的 ID 匹配
   */
  public signalAudioReady(syncId: string): void {
    // 确保是当前会话的信号
    if (this.state.currentSyncId === syncId && !this.state.isAudioReady) {
      console.log(`[SyncService] Audio is ready for ID: ${syncId}`);
      this.state.isAudioReady = true;
    }
  }

  /**
   * 清理会话
   */
  public endSession(): void {
    this.state.currentSyncId = null;
    this.state.isAudioReady = false;
  }
}

export const syncService = new SyncService();